extends Node2D

@onready var tileMap=$TileMap
# 放置模式
const PLACE_MODES=['canPlaceSeeds','canPlaceDirt']
enum LAYER{
    SEA,
    GROUND,
    GLASS
}
enum FARM_MODES{
    SEEDS,
    DIRT
}
# 放置状态
var farmState = FARM_MODES.DIRT
var dirtCoords = [] # 泥土坐标集合


func _unhandled_input(_event: InputEvent) -> void:
    if Input.is_action_just_pressed('toggleDirt'): 
        farmState=FARM_MODES.DIRT
    if Input.is_action_just_pressed('toggleSeeds'): 
        farmState=FARM_MODES.SEEDS
    if Input.is_action_just_pressed('click'):
        var mousePos=get_global_mouse_position()
        var coord=tileMap.local_to_map(mousePos) # 图块坐标
        var tileCoord=Vector2i(11,1) # 资源坐标

        if farmState == FARM_MODES.SEEDS:
            if getCustomData(coord,LAYER.GROUND,PLACE_MODES[farmState]):
                var level:=0
                var growLevel:=3
                handleSeed(coord,level,tileCoord,growLevel)
        elif farmState == FARM_MODES.DIRT:
            if getCustomData(coord,LAYER.GROUND,PLACE_MODES[farmState]):
                dirtCoords.append(coord)
                # 地形sets index参数， terrians index
                # 通过地形来添加
                tileMap.set_cells_terrain_connect(LAYER.GROUND,dirtCoords,2,0)
                
# 获取自定义参数
func getCustomData(coord,layer,property):
    var tileData:TileData=tileMap.get_cell_tile_data(layer,coord) 
    # 图块的自定义参数
    if tileData:
       return tileData.get_custom_data(property)
    else:
        return false


func handleSeed(coord,level,tileCoord,growLevel )->void:
    if level==growLevel:return
    var sourceID:=0
    var newCoord:Vector2i=Vector2i(tileCoord.x+level,tileCoord.y)
    tileMap.set_cell(LAYER.GLASS,coord,sourceID,newCoord)
    await get_tree().create_timer(5.0).timeout

    handleSeed(coord,level+1,newCoord,growLevel)